import {
  useIntersectionObserver,
  useIntervalFn
} from "@vueuse/core"
import {
  onMounted,
  ref
} from "vue"
import dayjs from 'dayjs'


/**
 * 
 * @param {Element} target 
 * @param {Function} apiFn 
 * @returns Array
 */
export const useLazyData = (apiFn) => {
  // target 是观察的目标dom容器，必须是dom容器，而且是vue3.0方式绑定的dom对象
  const target = ref(null)
  const data = ref([])

  // stop 是停止观察是否进入或移出可视区域的行为    
  const {
    stop
  } = useIntersectionObserver(target,
    // isIntersecting 是否进入可视区域，true是进入 false是移出
    async ([{
      isIntersecting
    }], observerElement) => {
      // 在此处可根据isIntersecting来判断，然后做业务
      if (isIntersecting) {
        stop()
        const {
          result
        } = await apiFn()
        data.value = result
      }
    }, {
      threshold: 0
    })

  return {
    target,
    data
  }
}


/**
 * 支付倒计时函数
 */
export const usePayTime = () => {
  const time = ref(0)
  const timeText = ref('')

  const {
    pause,
    resume
  } = useIntervalFn(() => {
    time.value--
    timeText.value = dayjs.unix(time.value).format('mm分ss秒')
    if (time.value < 0) {
      pause()
    }
  }, 1000, {
    immediate: false
  })

  /**
   * 倒计时开始的函数
   * @param {int} countdown 
   */
  const start = (countdown) => {
    time.value = countdown
    console.log(countdown);
    timeText.value = dayjs.unix(time.value).format('mm分ss秒')
    resume()
  }

  return {
    start,
    timeText
  }
}